package code.stack;

public class Stack {
    private int[] arr;
    private int top;

    public Stack(int capacity) {
        this.arr = new int[capacity];
        top = -1;
    }

    public void push(int element) {
        if (top == arr.length) {
            throw new IllegalStateException("栈已满！");
        }
        arr[++top] = element;
    }

    public int pop() {
        if (isEmpty()) {
            // 栈为空
            throw new IllegalStateException("栈为空！");
        }
        int item = arr[top];
        top--;
        return item;
    }

    public int top() {
        if (isEmpty()) {
            // 栈为空
            throw new IllegalStateException("栈为空！");
        }
        return arr[top];
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public int size() {
        return top+1;
    }

    public static void main(String[] args) {
        Stack stack = new Stack(5);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        System.out.println(stack.top()); // 5
        stack.pop();
        System.out.println(stack.top()); // 4
        System.out.println(stack.size()); // 4
    }
}
